/*
       Licensed to the Apache Software Foundation (ASF) under one
       or more contributor license agreements.  See the NOTICE file
       distributed with this work for additional information
       regarding copyright ownership.  The ASF licenses this file
       to you under the Apache License, Version 2.0 (the
       "License"); you may not use this file except in compliance
       with the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

       Unless required by applicable law or agreed to in writing,
       software distributed under the License is distributed on an
       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
       KIND, either express or implied.  See the License for the
       specific language governing permissions and limitations
       under the License.
 */

package com.mingyi;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.cordova.CordovaActivity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;

import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;

import cn.jpush.android.api.JPushInterface;

public class MainActivity extends CordovaActivity {

    // 测试:private static final String HOST = "http://www.snnyj.cn:8080/";
    // 正常：private static final String HOST = "http://www.mingyitech.cn:80/"
    // 吴：private static final String HOST = "http://180.168.141.108:8080/";
    private static final String HOST = "http://www.mingyitech.cn:80/";
    private AudioManager mAudioManager;
    private int localVersionCode = 0;

    private String localVersionName = "1.0";

    private String apkName = "MingYi.apk";

    private ConstomProgress pd;
    //private ProgressDialog pd = null;

    private long exitTime = 0;


    public static MainActivity instance;
    /* 记录进度条数量 */
    private int progress;
    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 上下文 */
    private Context mcontext;



    @Override
    public void onCreate(Bundle savedInstanceState) {

        instance =this;
        mAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
        super.onCreate(savedInstanceState);
        loadUrl(launchUrl);
        // 检查更新
        getLocalVersion(this);
        new Thread(task).start();


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 500) {
                exitTime = System.currentTimeMillis();
                return true;
            } else {
                // if (keyCode == KeyEvent.KEYCODE_BACK) {
                // 创建退出对话框
                AlertDialog isExit = new AlertDialog.Builder(this).create();
                // 设置对话框标题
                isExit.setTitle("系统消息");
                // 设置对话框消息
                isExit.setMessage("确定要退出\"宝贝呢\"？");
                // 添加选择按钮并注册监听
                isExit.setButton("确定", listener);
                isExit.setButton2("取消", listener);
                // 显示对话框
                isExit.show();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }


    /** 监听对话框里面的button点击事件 */
    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            switch (which) {
                case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
                    finish();
                    break;
                case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
                    break;
                default:
                    break;
            }
        }
    };


    private void getLocalVersion(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    "com.mingyi", 0);
            localVersionCode = info.versionCode;
            localVersionName = info.versionName;
            Log.e(TAG, "localVersionCode"+localVersionCode);
            Log.e(TAG, "localVersionName"+localVersionName);
        } catch (NameNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            if (data.containsKey("success")) {
                pd.cancel();
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setDataAndType(Uri.fromFile(new File(Environment
                                .getExternalStorageDirectory(), apkName)),
                        "application/vnd.android.package-archive");
               startActivity(intent);
               //android.os.Process.killProcess(android.os.Process.myPid());// 如果不加上这句的话在apk安装完成之后点击单开会崩溃
            }else if(msg.what==DOWNLOAD){
                pd.setProgress(progress);
            } else {
                StringBuffer sb = new StringBuffer();
                sb.append("当前版本：");
                sb.append(localVersionName);
                sb.append("，发现版本：");
                sb.append(data.getString("versionName"));
                sb.append("，是否更新？");
                Dialog dialog = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("软件更新")
                        .setMessage(sb.toString())
                        .setCancelable(false)
                        .setPositiveButton("立刻更新",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                      /*  pd = new ProgressDialog(
                                                MainActivity.this);
                                        pd.setTitle("正在下载");
                                        pd.setMessage("请稍后......");
                                        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);//设置水平进度条
                                       //pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                                      //  pd.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
                                        pd.setMax(100);
                                        pd.setCancelable(false);//设置进度条是否可以按退回键取消
                                        downAPK(HOST + apkName);
                                        // pd.setProgress(progress);*/
                                        pd = new ConstomProgress(MainActivity.this);
                                        pd.setMax(100);
                                        pd.setCancelable(false);//设置进度条是否可以按退回键取消
                                       // pd.setTitle(changeColor("正在下载",20));
                                        // pd.setMessage(changeColor("                   正在下载",20));
                                        pd.setMessage(changeColor("正在下载",20));
                                        //pd.setMessage(changeColor(getResources().getString(R.string.downLoading)));
                                        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                                        downAPK(HOST + apkName);
                                        //pd.show();

                                    }
                                }).create();
				/*
				 * .setNegativeButton("暂不更新", new
				 * DialogInterface.OnClickListener() {
				 * 
				 * @Override public void onClick(DialogInterface dialog, int
				 * which) { // ignore } }).create();
				 */
                // 显示更新框
                dialog.show();
            }
        }
    };

    // 下载APK
    public void downAPK(final String url) {
        pd.show();
        new Thread() {
            public void run() {
                HttpClient client = new DefaultHttpClient();
                HttpGet get = new HttpGet(url);

                try {
                    HttpResponse response = client.execute(get);
                    if (HttpStatus.SC_OK == response.getStatusLine()
                            .getStatusCode()) {
                        long length=response.getEntity().getContentLength(); //拿到文件大小
                        InputStream in = response.getEntity().getContent();
                        FileOutputStream out = new FileOutputStream(new File(
                                Environment.getExternalStorageDirectory(),
                                apkName));
                        byte[] b = new byte[1024];
                        int len = 0;
                        int j = 0;
                        //http://blog.csdn.net/lorinzhang/article/details/50442835
                        while ((len = in.read(b)) != -1){
                          /*  if(j<100){
                                Thread.sleep(300);
                                pd.incrementProgressBy(1);
                                j++;
                            }*/
                            j +=len;
                            progress = (int) (((float) j / length) * 100);
                          //  pd.setProgress(progress);
                            handler.sendEmptyMessage(DOWNLOAD);
                            Log.e(TAG, "progress:"+progress);
/*
                           // System.out.print(b.length);2000/100=20
                            int numread = in.read(b);
                            Log.e(TAG, "numread:"+numread);
                            j +=numread;
                            // 计算进度条位置
                        progress = (int) (((float) j / length) * 100);
                          *//*if(j<100){
                                Thread.sleep(300);
                                pd.incrementProgressBy(1);
                                j++;
                           }*//*
                            Log.e(TAG, "progress:"+progress);
                            pd.setProgress(progress);
                            //Thread.sleep(200);
                              //  pd.incrementProgressBy(progress);
                            *//*if (numread <= 0) {
                                // 下载成功关闭提示框
                                Message msg = handler.obtainMessage();
                                Bundle data = msg.getData();
                                data.putString("success", "true");
                                handler.sendMessage(msg);
                                break;
                            }*/
                            out.write(b, 0, len);
                        }
                        in.close();
                        out.close();
                      // 下载成功关闭提示框
                        Message msg = handler.obtainMessage();
                        Bundle data = msg.getData();
                        data.putString("success", "true");
                        handler.sendMessage(msg);

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }

    Runnable task = new Runnable() {
        @Override
        public void run() {
            String[] result = getServerVersion();

            int versionCode = result[0] == null ? 0 : Integer
                    .valueOf(result[0]);
            if (localVersionCode < versionCode) {
                Message msg = handler.obtainMessage();
                Bundle data = msg.getData();
                data.putString("versionCode", String.valueOf(versionCode));
                data.putString("versionName", result[1]);
                msg.setData(data);
                handler.sendMessage(msg);
            } else{
                Log.e(TAG,"versionCode"+versionCode);
                Log.e(TAG, "已是最新版本。");}
        }

        private String[] getServerVersion() {
            String[] result = new String[4];
            HttpClient client = new DefaultHttpClient();
            HttpParams params = client.getParams();
            HttpConnectionParams.setConnectionTimeout(params, 3000);
            HttpConnectionParams.setSoTimeout(params, 5000);
            HttpGet get = new HttpGet(HOST + "version.js");
            HttpResponse response;
            try {

                response = client.execute(get);
                if (HttpStatus.SC_OK == response.getStatusLine()
                        .getStatusCode()) {
                    JSONObject object = new JSONArray(EntityUtils.toString(
                            response.getEntity(), "UTF-8")).getJSONObject(0);
                    result[0] = object.getString("verCode");
                    result[1] = object.getString("verName");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    };

    public void ToJS(String jsCode){
        appView.sendJavascript(jsCode);
    }

    public String jsContent ="";
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if(hasFocus){
            if (jsContent != "") {
                String jsCode = "";
                jsCode = "xgPush.openFeature('" + jsContent + "')";
                ToJS(jsCode);
                jsContent = "";
            }
        }
    }
    //无声音，振动
    public void setRingerMode(boolean silent, boolean vibrate) {
        if (silent) {
            mAudioManager.setRingerMode(vibrate ? AudioManager.RINGER_MODE_VIBRATE :
                    AudioManager.RINGER_MODE_SILENT);
        } else {
            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
            mAudioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER,
                    vibrate ? AudioManager.VIBRATE_SETTING_ON
                            : AudioManager.VIBRATE_SETTING_OFF);
        }
    }
    public SpannableStringBuilder changeColor(String result,int size){
        SpannableStringBuilder spanBuilder = new SpannableStringBuilder(result);
        //Color.BLUE
        spanBuilder.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.blue)), 0, result.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        //new AbsoluteSizeSpan(size,true),不加true的话，它取px像素；加了true,则是android默认尺寸sp
        spanBuilder.setSpan(new AbsoluteSizeSpan(size,true),0,result.length(),Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        return spanBuilder;
    }
}
